import { Directive, OnInit, Input, Output, EventEmitter, HostListener, OnDestroy } from '@angular/core'
import { Subject, Subscription, of } from 'rxjs'
import { debounceTime, switchMap } from 'rxjs/operators'

@Directive({
  selector: '[appDebounceClick]',
})
export class DebounceClickDirective implements OnInit, OnDestroy {
  @Input()
  debounceTime = 500

  @Output()
  debounceClick = new EventEmitter()

  private clicks$ = new Subject()
  private subscription: Subscription

  constructor() {}

  ngOnInit() {
    this.subscription = this.clicks$.pipe(
      debounceTime(this.debounceTime),
      switchMap(e => of(e)),
    ).subscribe(e => this.debounceClick.emit(e))
  }

  ngOnDestroy() {
    this.subscription.unsubscribe()
  }

  @HostListener('click', ['$event'])
  clickEvent(event: MouseEvent) {
    event.preventDefault()
    event.stopPropagation()
    this.clicks$.next(event)
  }
}
